package router

import (
	"bs/server"
	"bs/sql"
	"strings"

	"github.com/gin-contrib/cors"
	"github.com/gin-gonic/gin"
)

func SetupRouter(db *sql.DB) *gin.Engine {
	r := gin.Default()

	// 配置 CORS
	r.Use(cors.New(cors.Config{
		AllowOrigins:     []string{"http://localhost:3000"},
		AllowMethods:     []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"},
		AllowHeaders:     []string{"Origin", "Content-Type", "Accept", "Authorization"},
		ExposeHeaders:    []string{"Content-Length"},
		AllowCredentials: true,
	}))

	// 1. 登录接口
	r.POST("/api/login", func(c *gin.Context) {
		server.Login(c, db)
	})

	// 2. 注册接口
	r.POST("/api/users", func(c *gin.Context) {
		server.CreateUser(c, db)
	})

	// 创建路由组 /api，并应用 Token 校验中间件
	apiGroup := r.Group("/api")
	apiGroup.Use(AuthMiddleware())
	{

		//查看所有用户
		apiGroup.GET("/users", func(c *gin.Context) {
			server.GetUsers(c, db)
		})
		//编辑用户
		apiGroup.PUT("/users/:id", func(c *gin.Context) {
			server.UpdateUser(c, db)
		})
		//删除用户
		apiGroup.DELETE("/users/:id", func(c *gin.Context) {
			server.DeleteUser(c, db)
		})

		//赛事管理

		//查看所有赛事
		apiGroup.GET("/events", func(c *gin.Context) {
			server.GetEvents(c, db)
		})
		//录入赛事
		apiGroup.POST("/events", func(c *gin.Context) {
			server.CreateEvents(c, db)
		})
		//修改赛事
		apiGroup.PUT("/events/:id", func(c *gin.Context) {
			server.UpdateEvent(c, db)
		})

		//报名管理

		//查看所有报名
		apiGroup.GET("/registrations", func(c *gin.Context) {
			server.GetResgistration(c, db)
		})
		//新增报名
		apiGroup.POST("/registrations", func(c *gin.Context) {
			server.CreateRegistration(c, db)
		})

		//成绩管理

		//查看所有成绩
		apiGroup.GET("/results", func(c *gin.Context) {
			server.GetResult(c, db)
		})
		//录入成绩
		apiGroup.POST("/results", func(c *gin.Context) {
			server.CreateResult(c, db)
		})
		//生成成绩册
		apiGroup.POST("/results/report", func(c *gin.Context) {
			server.GenerateResult(c, db)
		})
		//生成秩序册
		apiGroup.POST("/events/order", func(c *gin.Context) {
			server.GenerateOrder(c, db)
		})
	}

	return r
}

func AuthMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		authHeader := c.GetHeader("Authorization")
		if authHeader == "" {
			c.AbortWithStatusJSON(401, gin.H{"error": "Authorization header is required"})
			return
		}

		tokenParts := strings.Split(authHeader, " ")
		if len(tokenParts) != 2 || tokenParts[0] != "Bearer" {
			c.AbortWithStatusJSON(401, gin.H{"error": "Invalid token format"})
			return
		}

		token := tokenParts[1]
		if token == "" {
			c.AbortWithStatusJSON(401, gin.H{"error": "Token is empty"})
			return
		}

		c.Set("token", token)
		c.Next()
	}
}
